<template>
  <!-- 模板内容保持不变 -->
  <s-layout>

    <!-- 筛选和排序区域 -->
    <view class="filter-section">
      <!-- 美化后的搜索框 -->
      <view class="search-container">
        <input v-model="searchKeyword" type="text" placeholder="输入关键词搜索" @input="handleSearch" class="search-input" />
        <fui-icon name="search" size="24" color="#666" class="search-icon"></fui-icon>
      </view>
      <picker mode="selector" :range="timeRangeLabels" @change="handleTimeRangeChange">
        <view class="filter-item" >
          <text class="selector-text">{{ timeRangeLabels[selectedTimeRangeIndex] }}</text>
          <image class="selector-icon" src="@/static/tabs/设置.png" mode="aspectFit" />
        </view>
      </picker>
    </view>

    <!-- 任务列表 -->
    <view class="enterprise-card">
      <view class="container">

        <!-- 任务列表 -->
        <view v-for="task in tasks" class="task-card" @click="handleTaskClick(task)">
          <!-- 状态标签 -->
          <view class="status-corner" :class="task.status === '已完成' ? 'pending':'completed'  ">
            <text class="status-text">{{ task.status }}</text>
          </view>
          <view class="card-header2" style="align-items: flex-end;">
          </view>
          <view class="task-title">
            <view class="task-tag" :style="{
              backgroundColor: task.tagColor || '#2b85e4',
              border: `2rpx solid ${task.tagColor || '#2b85e4'}`,
              background: 'transparent',
              color: task.tagColor || '#2b85e4',
              textAlign: 'center'
            }">
              {{ task.tag }}
            </view>
            <text class="title-text">{{ task.name.length > 11 ? task.name.substring(0, 11) + '...' : task.name }}</text>
          </view>
          <!-- 添加任务简介框 -->
          <view class="task-description">
            <text class="description-text">{{ task.describe.length > 20 ? task.describe.substring(0, 20) + '...' :
              task.describe }}</text>
            <view v-if="task.describe.length > 20" class="detail-button" @click.stop="showTaskDetail(task)">
              <text>详情</text>
            </view>
          </view>
          <view class="card-content">
            <view class="time-container">
              <fui-timeaxis background="#fff" :padding="['0rpx', '0rpx']" lineWidth="0.2">
                <fui-timeaxis-node :lineColor="index < 3 ? item.activeColor : '#ccc'"
                  :lined="index !== task.processData.length - 1" v-for="(item, index) in task.processData" :key="index">
                  <view class="fui-node" :style="{ borderColor: item.activeColor }">
                  </view>
                  <template v-slot:right>
                    <view class="fui-process__node" :class="{ 'fui-node__pb': index !== task.processData.length - 1 }">
                      <view class="fui-title" :style="{ color: index === 3 ? item.activeColor : '#181818' }">{{
                        item.title }}
                      </view>
                      <view class="fui-descr" v-if="item.descr">{{ item.descr }}</view>
                      <view class="fui-time">{{ item.time }}</view>
                    </view>
                  </template>
                </fui-timeaxis-node>
              </fui-timeaxis>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 批量操作按钮 -->
    <view class="batch-actions" v-if="selectedTasks.length > 0">
      <fui-button type="primary" @click="batchComplete">批量完成</fui-button>
      <fui-button type="warn" @click="batchDelete">批量删除</fui-button>
    </view>
  </s-layout>

  <!-- 任务详情弹窗 -->
  <view class="modal-overlay" v-if="showDetailModal" @click="closeTaskDetail">
    <view class="modal-content" @click.stop>
      <view class="modal-header">
        <text class="modal-title">任务详情</text>
        <view class="modal-close" @click="closeTaskDetail">×</view>
      </view>
      <scroll-view class="modal-body" scroll-y>
        <view class="modal-task-title">{{ currentTaskDetail?.name }}</view>
        <view class="modal-task-tag" :style="{
          color: currentTaskDetail?.tagColor || '#2b85e4',
          borderColor: currentTaskDetail?.tagColor || '#2b85e4'
        }">{{ currentTaskDetail?.tag }}</view>
        <view class="modal-description-title">任务简介:</view>
        <view class="modal-description">{{ currentTaskDetail?.describe }}</view>
      </scroll-view>
      <view class="modal-footer">
        <button class="modal-button" @click="closeTaskDetail">关闭</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import sheep from "@/sheep";
import { onLoad } from "@dcloudio/uni-app";
const searchKeyword = ref('')
// 任务数据
const tasks = ref([
  {
    id: 1,
    name: 'UI设计',
    status: '进行中',
    priority: '高',
    type: '设计任务',
    describe: "组织消防应急演练,模拟火灾发生,提高人员安全意识和应急响应能力",
    progressPercent: "70",
    createdAt: '2023-10-01',
    offsetX: 0,
    tag: '行业',
    tagColor: "#2b85e4",
    processData: [
      {
        title: '开始时间',
        time: '2023/10/01 09:00',
      },
      {
        title: '预计结束时间',
        time: '2028/12/31 18:00',
      }
    ]
  },
  // 其他任务数据...
  {
    id: 2,
    name: 'API开发',
    priority: '中',
    offsetX: 0,
    describe: "组织消防应急演练,模拟火灾发生,提高人员安全意识和应急响应能力",
    progressPercent: "70",
    tag: '单位',
    tagColor: "#FF5722",
    processData: [
      {
        title: '开始时间',
        time: '2023/09/20 10:00',
      },
      {
        title: '预计结束时间',
        time: '2023/11/15 17:00',
      }
    ]
  },
  // 其他任务数据...
])
// 定义两个数组：一个用于显示，一个用于实际值
const timeRangeValues = ref([0,3, 7, 15, 30,365]);
const timeRangeLabels = ref(['全部','近3天', '近7天', '近15天', '近30天','近一年']);
const selectedTimeRangeIndex = ref(0);

// 修改处理方法，使用实际的天数值
const handleTimeRangeChange = (e) => {
  selectedTimeRangeIndex.value = e.detail.value;
  const days = timeRangeValues.value[selectedTimeRangeIndex.value];
  console.log('选择了天数:', days);
  // 使用实际的 API 调用，获取指定天数范围内的任务
  fetchTasks(days);
};

// 添加过滤任务的函数
const fetchTasks = (days) => {
  // 调用 API 获取特定时间范围内的任务
  console.log(`获取最近${days}天的任务`);
  
  // 准备API参数
  const params = {
    third_company_id: sheep.$store("user").userInfo.company_id,
    day: days
  };
  
  // 如果有搜索关键词，添加到参数中
  if (searchKeyword.value) {
    params.t_name = searchKeyword.value;
  }
  
  uni.showLoading({ title: '加载中...' });
  
  // 调用API获取任务列表
  sheep.$api.other.getTaskList(params).then(res => {
    if (res.code === 200) {
      console.log("获取到的任务列表aaaaaa:", res.taskList);
      tasks.value = res.taskList.map(item => {
        // 根据t_status状态确定任务状态
        let status = '未开始';
        
        if (item.t_state == 1) {
          status = '评估中';
        } else if (item.t_state == 2) {
          status = '已完成';
        }
        
        // 根据任务类型设置标签和颜色
        let tag = '行业';
        let tagColor = '#2b85e4';
        
        if (item.t_type == '1') {
          tag = '区域';
          tagColor = '#FF5722';
        } else if (item.t_type == '3') {
          tag = '单位';
          tagColor = '#00C853';
        }
        
        return {
          id: item.t_id,
          name: item.t_name,
          de_name: '消防部门', // 可根据实际情况设置，这里使用默认值
          status: status,
          describe: item.t_describe || "暂无描述",
          tag: tag,
          company_id:item.company_id,
          tagColor: tagColor,
          progressPercent: item.t_progress || "0",
          createdAt: item.createtime || new Date().toISOString().split('T')[0],
          offsetX: 0,
          // 保留 t_num 字段，用于判断跳转逻辑
          t_num: item.t_num || 0,
          processData: [
            {
              title: '开始时间',
              time: item.t_s_date ? item.t_s_date.replace(/-/g, '/') : new Date().toISOString().split('T')[0].replace(/-/g, '/'),
              activeColor : "#465CFF"
            },
            {
              title: '结束时间',
              time: item.t_e_date ? item.t_e_date.replace(/-/g, '/') : new Date().toISOString().split('T')[0].replace(/-/g, '/'),
             activeColor : status === '已完成' ? "#465CFF" : ''
            }
          ]
        };
      });
      
      console.log("获取到的任务列表:", tasks.value);
    } else {
      uni.showToast({ title: res.msg || '获取任务失败', icon: 'none' });
    }
    uni.hideLoading();
  }).catch(err => {
    console.error('获取任务列表失败:', err);
    uni.hideLoading();
    uni.showToast({ title: '网络异常，请重试', icon: 'none' });
  });
};


// 批量操作
const selectedTasks = ref([])
const batchComplete = () => {
  selectedTasks.value.forEach(task => {
    task.status = '已完成'
  })
  selectedTasks.value = []
}

const batchDelete = () => {
  tasks.value = tasks.value.filter(task => !selectedTasks.value.includes(task))
  selectedTasks.value = []
}

// 添加导航方法
const navigateToDetail = (enterprise) => {
  console.log("enterprise", enterprise);
    uni.navigateTo({
      url: `/pages/other/qydetails/qytail?company_id=${
        enterprise.company_id
      }&task_id=${enterprise.id}`,
    });
};

const handleTaskClick = (task) => {
  console.log("task",task);
  // 根据 t_num 值来判断跳转逻辑
  if (task.t_num && task.t_num > 1) {
    // 如果 t_num 大于 1，跳转到任务企业列表
    uni.navigateTo({
      url: `/pages/xf/taskEnterpriseList?t_id=${task.id}`,
    });
  } else {
    // 否则跳转到任务详情页
    navigateToDetail(task);
  }
};
// 添加搜索处理方法
const handleSearch = () => {
  // 根据当前选择的时间范围获取天数
  const days = timeRangeValues.value[selectedTimeRangeIndex.value];
  // 重新获取任务列表，会自动包含搜索关键词
  fetchTasks(days);
};

// 在组件加载时获取任务列表
onLoad(() => {
  // 默认获取全部的任务
  fetchTasks(timeRangeValues.value[selectedTimeRangeIndex.value]);
});

const currentTaskDetail = ref(null);
const showDetailModal = ref(false);

const showTaskDetail = (task) => {
  currentTaskDetail.value = task;
  showDetailModal.value = true;
};

const closeTaskDetail = () => {
  showDetailModal.value = false;
};
</script>

<style lang="scss" scoped>
/* 以下样式从 index.vue 复制过来 */
.enterprise-card {
  background: #ffffff;
  border-radius: 5px;
  width: 96%;
  margin: 0 auto;
  margin-top: 15rpx;
  box-shadow: 0 12rpx 48rpx rgba(82, 137, 255, 0.08);
}

.card-header {
  padding: 20rpx 20rpx;
}

.task-card {
  background: #fcfcfc;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 1rpx 4rpx 12rpx rgba(0, 0, 0, 0.1);
  position: relative;
}

.status-corner {
  position: absolute;
  top: 0;
  right: 0;
  width: 120rpx;
  height: 120rpx;
  background: #ff4d4f;
  clip-path: polygon(0 0, 100% 0, 100% 100%);
  border-top-right-radius: 16rpx;
  display: flex;
  justify-content: flex-end;
  align-items: flex-start;
  padding: 10rpx;

  &.completed {
    background: #52c41a;
  }

  &.pending {
    background: #4c3af3;
  }

  .status-text {
    font-size: 24rpx;
    color: #fff;
    font-weight: bold;
    position: absolute;
    top: 40%;
    left: 54%;
    transform: translate(-40%, -60%) rotate(45deg);
    white-space: nowrap;
    padding: 4rpx;
    width: 100%;
    text-align: center;
    overflow: visible;
    transform-origin: center center;
  }
}

.completed {
  background: #e6f7ff;
  color: #1890ff;
}

.pending {
  background: #fff1f0;
  color: #ff4d4f;
}

.task-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 20rpx;
  position: relative;
  padding-left: 70rpx;

  .task-tag {
    position: absolute;
    left: -5rpx;
    top: 50%;
    transform: translateY(-50%);
    width: 60rpx;
    height: 60rpx;
    border-radius: 8rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: 24rpx;
    font-weight: bold;
  }
}


.card-content {
  margin-top: 20rpx;
}


.time-container {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.container {
  width: 94%;
  margin: auto;
  border-radius: 5px;
  background-color: #fff;
}

/* 保留 alltasks.vue 中独有的样式 */
.filter-section {
  display: flex;
  justify-content: space-between;
  padding: 20rpx;
  background: #fff;
}

.filter-item {
  display: flex;
  align-items: center;
  padding: 10rpx 20rpx;
  border: 1rpx solid #eee;
  border-radius: 8rpx;
}

.search-container {
  display: flex;
  align-items: center;
  border: 1rpx solid #ccc;
  border-radius: 8rpx;
  background-color: #fff;
  padding: 10rpx 20rpx;
}

.search-input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 28rpx;
  color: #333;
  background-color: transparent;
}

.search-icon {
  margin-left: 10rpx;
}

.batch-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-around;
  padding: 20rpx;
  background: #fff;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.fui-node {
  width: 32rpx;
  height: 32rpx;
  border-radius: 50%;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 4px solid #ccc;
  box-sizing: border-box;
}

.fui-process__node {
  padding-left: 20rpx;
}

.fui-node__pb {
  padding-bottom: 48rpx;
}

.fui-title {
  font-size: 30rpx;
  line-height: 34rpx;
  font-weight: bold;
}

.fui-descr {
  font-size: 28rpx;
  padding-top: 12rpx;
  color: #7F7F7F;
}

.fui-time {
  font-size: 24rpx;
  color: #B2B2B2;
  padding-top: 12rpx;
}

.time-range-selector {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16rpx 24rpx;
  background: #fff;
  border-radius: 12rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
}

.selector-box {
  display: flex;
  align-items: center;
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
  background-color: #f5f7fa;

  .selector-text {
    font-size: 28rpx;
    color: #b83131;
    margin-right: 8rpx;
  }
}

.selector-icon {
  width: 30rpx;
  height: 30rpx;
}

.all-task-link {
  display: flex;
  align-items: center;
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
  background-color: #e6f7ff;

  text {
    font-size: 28rpx;
    color: #1890ff;
    margin-right: 8rpx;
  }

  &:active {
    background-color: #bae7ff;
  }
}

.progress-box {
  position: absolute;
  bottom: 10rpx;
  right: 10rpx;
  background-color: #2b85e4;
  border-radius: 8rpx;
  padding: 8rpx 16rpx;
  color: #fff;
  font-weight: bold;
  font-size: 24rpx;
}

.ghost-button {
  background-color: transparent;
  border: 2rpx solid #2b85e4;
  color: #2b85e4;
}

// 添加任务简介的样式
.task-description {
  background-color: #f5f7fa;
  border-radius: 12rpx;
  padding: 16rpx 20rpx;
  margin: 10rpx 0 20rpx 0;
  font-size: 26rpx;
  color: #666;
  border-left: 6rpx solid #2b85e4;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.description-text {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.detail-button {
  padding: 6rpx 16rpx;
  background-color: #e6f7ff;
  border-radius: 8rpx;
  margin-left: 16rpx;
  font-size: 24rpx;
  color: #2b85e4;
  font-weight: 500;
}

// 模态窗口样式
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.modal-content {
  width: 80%;
  max-height: 80%;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.modal-header {
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.modal-close {
  font-size: 40rpx;
  color: #999;
  cursor: pointer;
}

.modal-body {
  padding: 30rpx;
  flex: 1;
  max-height: 60vh;
}

.modal-task-title {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.modal-task-tag {
  display: inline-block;
  padding: 6rpx 16rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
  font-weight: 500;
  border: 2rpx solid;
  background-color: transparent;
  margin-bottom: 30rpx;
}

.modal-description-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 16rpx;
}

.modal-description {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
}

.modal-footer {
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #eee;
  display: flex;
  justify-content: flex-end;
}

.modal-button {
  padding: 16rpx 40rpx;
  background-color: #2b85e4;
  color: #fff;
  border-radius: 8rpx;
  font-size: 28rpx;
  font-weight: 500;
}
</style>